import { Component, OnInit } from '@angular/core'
import { ActivatedRoute, Params } from '@angular/router'
import { Location } from '@angular/common'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { ActivityService } from './services/activity.service'

@Component({
  selector: 'app-activity',
  templateUrl: './activity.component.html',
  styleUrls: ['./activity.component.scss']
})
export class ActivityComponent implements OnInit {
  // 楼盘ID
  project = ''

  // 列表
  list = []
  nomore = false
  error = false
  loading = false

  constructor(
    private location: Location,
    private activatedRoute: ActivatedRoute,
    private utils: CommonUtil,
    private service: ActivityService
  ) {
    // 触底翻页
    window.onscroll = e => {
      let clientHeight = document.documentElement.clientHeight
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      let scrollHeight = document.body.scrollHeight
      // 触底了
      if (scrollTop + clientHeight === scrollHeight) {
        setTimeout(() => {
          if (!this.nomore && !this.error) {
            this.getList(this.service.reqdata.pager.Start)
          }
        }, 1000)
      }
    }
  }

  // 初始化
  ngOnInit() {
    this.loading = true
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      if (params.project) {
        this.service.project = params.project
      }
      this.getList(0)
    })
  }
  // 返回
  onClickLeft() {
    this.location.back()
  }
  // 获取列表
  getList(start) {
    this.service.getList(
      start,
      res => {
        setTimeout(() => {
          this.error = false
          this.loading = false
        }, 500)
        if (res.Success && res.Result) {
          // 下一次的起始条目需要加上本次请求到的数据条数
          this.service.reqdata.pager.Start += res.Result.Value.length
          // 如果本次请求到的数据小于每页总数，说明没有下一页了
          if (res.Result.Value.length < this.service.reqdata.pager.Limit) {
            this.nomore = true
          } else {
            this.nomore = false
          }
          // 数据处理
          let data = res.Result.Value.map(item => {
            let Photo = this.utils.getThumbnail(item.Photo)
            let obj = {
              Id: item.Id,
              Title: item.Title,
              Start: item.Start,
              End: item.End,
              Photo: Photo,
              Join: item.Join
            }
            return obj
          })
          // 如果是第一页，那先把数据清空
          if (start === 0) {
            this.list = []
          }
          this.list = this.list.concat(data)
        } else {
          this.nomore = false
        }
      },
      err => {
        setTimeout(() => {
          this.error = true
          this.loading = false
        }, 500)
      }
    )
  }
  // 列表性能优化
  trackByFn(index, item) {
    return item.Id
  }
  // 刷新
  handleReload() {
    this.error = false
    this.loading = true
    this.getList(this.service.reqdata.pager.Start)
  }
}
